var Niep = {
    init: function (configs) {
        for (var key in configs) {
            NP_config[key] = configs[key]
        }
        NP_DATA['startParams'] = t_getUrlParamsJson();
        var uid = getCookie('NIEP_UUID');
        if (!uid) {
            uid = generateUUID();
            setCookie('NIEP_UUID', uid, 30)
        }
        NP_DATA['cookieUid'] = uid;
        NP_component.loadResources()
    },
    getShowPage: function () {
        return $('.' + NP_config.baseClass + '.' + NP_config.showClass)
    },
    get: function (params, index) {
        var arr = params.split('-');
        return arr[index]
    }
};
var NP_config = {
    loadingImg: '/carworld_weixin/images/NP_loading.gif',
    showClass: 'page-show',
    baseClass: 'page',
    menuId: 'menu',
    menuItemClass: 'item',
    menuShowClass: 'cur',
    host: getHost(),
    service: getHost(),
    start: 'N.',
    end: '.L',
    loginPageId: 'page_login',
    pageRoute: '/carworld_weixin/pages',
    //defaultPage: 'index',
    defaultParams: ''
};
var NP_DATA = {
    startParams: null,
    historyAction: null,
    pageParams: {},
    cookieUid: null
};

function getHost() {
    var h = location.href;
    var p = location.pathname;
    return h.substr(0, h.indexOf(p))
}
function t_getUrlParamsJson() {
    var paramsJson = {
        //page: NP_config.defaultPage,
        params: NP_config.defaultParams
    };
    var href = location.href;
    var queryStr = location.search;
    NP_DATA['historyAction'] = href.replace(queryStr, '');
    if (!queryStr) return paramsJson;
    var arr = location.search.substring(1).split("&");
    for (var i = 0; i < arr.length; i++) {
        var pairs = arr[i];
        var pos = pairs.indexOf('=');
        if (pos == -1) continue;
        paramsJson[pairs.substring(0, pos)] = decodeURI(pairs.substring(pos + 1))
    }
    return paramsJson
}
function generateUUID() {
    var d = new Date().getTime();
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16)
    })
}
function setCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString()
    } else expires = "";
    document.cookie = name + "=" + value + expires + "; path=/"
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length)
    }
    return null
}
var NP_component = {
    loading: function (isLoading) {
        var loading = $('#NP_loading');
        if (loading.length == 0) {
            loading = $('<div id="NP_loading" style="position: fixed;top: 0;left: 0;right: 0;bottom: 0;z-index: 20170107;text-align: center;"><img style="height: 26px;width: 26px;position: absolute;top: 50%;margin-top: -13px;left: 50%;margin-left: -13px;" src="' + NP_config.loadingImg + '"/></div>');
            $('body').append(loading)
        }
        if (isLoading) {
            loading.show()
        } else {
            loading.hide()
        }
    },
    /*setMemu: function (targetPage) {
        var menu = $('#menu');
        if (menu.length == 0 || targetPage.length == 0) return false;
        var tm = targetPage.data('menu');
        if ( !! tm && tm != '-1') {
            var items = menu.find('.item');
            items.removeClass(NP_config.menuShowClass);
            items.removeClass('sec');
            items.each(function (i) {
                var sort = $(this).data('sort');
                if (sort == tm) {
                    $(this).addClass(NP_config.menuShowClass)
                }
            });
            menu.find('.item').not('.cur').eq(1).addClass('sec');
            menu.show()
        } else {
            menu.hide()
        }
    },*/
    scroll: function (targetPage) {
        var pos = targetPage.attr('data-pos');
        if (!pos) pos = 0;
        $('body').scrollTop(pos)
    },
    loadHtml: function (fileName) {
        var url = NP_config.host + NP_config.pageRoute + "/" + fileName;
        alert('loadHtml:'+url);
        var html = null;
        $.ajax({
            url: url,
            async: false,
            type: "post",
            dataType: 'text',
            success: function (result) {
                var holder = new RegExp(NP_config.start + 'host' + NP_config.end, "g");
                var val = NP_config.host;
                result = result.replace(holder, val);
                html = $(result);
                $('body').prepend(html)
            }
        });
        return html
    },
    fill: function (baseHtml, data, isPrev) {
        var html = baseHtml.toString();
        var holder, val, obj;
        if (!data) {
            data = {}
        }
        data['host'] = NP_config.host;
        for (var key in data) {
            holder = new RegExp("N." + key + '.L', "g");
            val = data[key];
            html = html.replace(holder, val)
        }
        obj = $(html);
        NP_component.loadImg(obj, isPrev);
        return obj
    },
    preloadPage: function (showingPage) {
        var preloads = showingPage.attr('data-preload');
        if (!preloads) return false;
        var items = preloads.split(',');
        var fileName, existPage;
        for (var i = 0; i < items.length; i++) {
            fileName = items[i];
            existPage = $('#page_' + fileName);
            if (existPage.length == 0) {
                NP_component.loadPage(fileName, function (res, pageId) {
                    var page = $(res);
                    page.attr('id', 'page_' + pageId);
                    $('body').prepend(page)
                })
            }
        }
    },
    loadPage: function (pageId, success) {
        var url = NP_config.host + NP_config.pageRoute + "/page_" + pageId + ".html";
        var loader = NP_component.createLoader();
        loader.load(url, function (result, status) {
            if (status == 'success') {
                var holder = new RegExp(NP_config.start + "host" + NP_config.end, "g");
                result = result.replace(holder, NP_config.host).replace(new RegExp(NP_config.start + "service" + NP_config.end, "g"), NP_config.service).replace(new RegExp(NP_config.start + "cid" + NP_config.end, "g"), NP_DATA.cookieUid);
                if ($.isFunction(success)) {
                    success(result, pageId)
                }
            } else {
                console.error('[niepErro]：page_' + pageId + ".html不存在")
            }
        });
        loader.empty()
    },
    createLoader: function () {
        var loader = $('#NP_loader_container');
        if (loader.length != 0) return loader;
        loader = $('<div id="NP_loader_container" style="display: none;"></div>');
        $('body').append(loader);
        return loader
    },
    loadResources: function (params, targetPage, drawBoard) {
        var startPage = NP_DATA.startParams.page;
        if (!startPage) {
            NP_component.request(params, targetPage)
        } else {
            NP_component.loading(true);
            NP_component.loadPage(startPage, function (result) {
                var page = $(result);
                page.find('[data-prev="true"]').each(function () {
                    $(this).attr('data-prev', false)
                });
                page.attr('id', 'page_' + startPage);
                $('body').prepend(page);
                NP_DATA.startParams['page'] = '';
                NP_component.request(NP_DATA.startParams.params, page)
            })
        }
    },
    request: function (params, target) {
        var clone = target.data('clone');
        if (clone) {
            var targetId = target.attr('id');
            var attachTimes = NP_DATA.pageParams[targetId + '_' + params];
            var cloneTarget = $("#" + targetId + "_" + attachTimes);
            if (cloneTarget.length == 0) {
                target = $(target.clone());
                var times = new Date().getTime();
                NP_DATA['pageParams'][targetId + '_' + params] = times;
                target.attr({
                    'id': targetId + "_" + times,
                    'data-clone': 'cloneBody',
                    'data-pageparams': params,
                    'data-ontology': targetId
                });
                $('body').append(target)
            } else {
                target = cloneTarget
            }
        }
        
        
        NP_component.title(target);
        target.attr('data-params', params);
        var html = target.html();
        html = html.replace(new RegExp(NP_config.start + "params" + NP_config.end, "g"), params);
        target.html($(html));
        var cmds = target.find('[data-unload="once"],[data-unload="refresh"],[data-unload="static"]');
        NP_component.getData(target, params);
        if (cmds.length == 0) {
            target.pageShow()
        }
    },
    getData: function (targetPage, params) {
        var cmds = targetPage.find('[data-unload="once"],[data-unload="refresh"],[data-unload="static"]');
        targetPage.attr('data-count', cmds.length);
        cmds.each(function () {
            var ts = $(this);
            var cmd = eval(ts.data('cmd'));
            new cmd(ts, decodeURI(params), targetPage);
            if (ts.data('unload') == 'once') {
                ts.attr('data-unload', false)
            } else if (ts.data('unload') == 'static') {
                ts.attr('data-unload', 'loaded')
            }
        })
    },
    loadImg: function (ts, isPrev) {
        ts.find('img').each(function () {
            var cur = $(this);
            var defUrl = cur.data('default');
            if (isPrev == true) {
                if ( !! defUrl) {
                    cur.attr('src', defUrl)
                }
            } else {
                var loading = cur.data('loading');
                if ( !! loading && loading != 'null') {
                    cur.attr('src', loading)
                } else if ( !! defUrl) {
                    cur.attr('src', defUrl)
                }
            }
        })
    },
    component: [],
    setComponent: function (ele, html) {
        var params = !! ele.data('params') ? ele.data('params') : '';
        NP_component.component[ele.data('cmd') + params] = html
    },
    getComponent: function (ele) {
        var params = !! ele.data('params') ? ele.data('params') : '';
        var keys = ele.data('cmd') + params;
        var jsons = NP_component.component;
        for (key in jsons) {
            if (key == keys) {
                return jsons[key]
            }
        }
    },
    getEleHtml: function (ele) {
        var parent = $('<div></div>');
        parent.append(ele.clone());
        return parent.html()
    },
    backUrl: '',
    login: function (loginPageId) {
        if (!loginPageId) {
            loginPageId = NP_config.loginPageId
        }
        var curAddr = NP_component.backUrl;
        if (!curAddr) {
            NP_component['backUrl'] = window.location.href;
            curAddr = NP_component.backUrl
        }
        NP_component.switchPage({
            target: '#' + loginPageId,
            params: curAddr
        })
    },
    switchPage: function (params) {
        if (!params) {
            console.error('switchPage(params)中params参数缺失')
        } else if (!('target' in params)) {
            console.error('switchPage(params)中target参数缺失')
        }
        var target = params.target;
        var switchBtn = $('<a href="" data-action="switch" data-params="" style="display:none">switchPage</a>');
        switchBtn.attr('href', target);
        switchBtn.attr('data-params', params.params);
        var showPage = Niep.getShowPage();
        if (showPage.length == 0) {
            showPage = $('body')
        }
        showPage.append(switchBtn);
        switchBtn.click()
    },
    small: function (tips, time, isTop) {
        var name = isTop ? 'top' : 'bottom';
        var tipBtn = $("<div style='width:100% ; position:fixed ;text-align:center; " + name + ":20%;left:0;' ><span style='background:#000;color:#fff;padding:10px 15px ; border-radius:4px'>" + tips + "</span></div>");
        $('body').append(tipBtn);
        if (!time) time = 3000;
        tipBtn.fadeOut(time)
    },
    reloadPage: function (pages) {
        for (var i = 0; i < pages.length; i++) {
            var ts = $('#page_' + pages[i]).find('[data-unload="false"]');
            ts.attr('data-unload', 'once').attr('pageNum', 1)
        }
    },
    refreshCmd: function (cmd) {
        $('[data-cmd="' + cmd + '"]').each(function () {
            if ($(this).attr('data-unload') == 'false') {
                $(this).attr('data-unload', 'once')
            }
        })
    },
    title: function (target) {
        var title = target.data('title');
        if ( !! title) {
            document.title = title
        } else {
            document.title = NP_config.title
        }
    },
    getShowPage: function () {
        return $('.' + NP_config.showClass + "." + NP_config.baseClass)
    }
};
var NP_history = {
    list: [],
    push: function (historyPage, targetPageId, params) {
        var id = historyPage.attr('id');
        var list = NP_history.list;
        var last = list[list.length - 1];
        if (list.length == 0 || id != last.id) {
            targetPageId = "page=" + targetPageId.split('_')[1];
            if ( !! params) {
                targetPageId = targetPageId + "&params=" + params
            }
            if ( !! NP_DATA.historyAction) {
                targetPageId = NP_DATA.historyAction + "?" + targetPageId
            }
            history.pushState(id, id, targetPageId);
            list.push({
                id: id,
                html: historyPage.html()
            })
        }
    },
    back: function () {
        var list = NP_history.list;
        if (list.length > 0) {
            var target = list.pop();
            Niep.getShowPage().niepHide();
            var historyPage = $('#' + target.id);
            NP_component.loading(false);
            historyPage.html(target.html).niepShow();
            NP_component.scroll(historyPage);
            NP_component.setMemu(historyPage);
            NP_component.title(historyPage)
        }
    }
};
(function ($) {
    $.fn.pageShow = function () {
        var obj = this;
        if ($.isFunction(NP_config.beforePageShow)) {
            NP_config.beforePageShow(obj)
        }
        obj.loadStaticImg();
        NP_component.setMemu(obj);
        NP_component.loading(false);
        $('#loading').fadeOut();
        $('.' + NP_config.baseClass).removeClass('.' + NP_config.showClass);
        obj.niepShow();
        NP_component.scroll(obj);
        NP_component.preloadPage(obj);
        if ($.isFunction(NP_config.afterPageShow)) {
            NP_config.afterPageShow(obj)
        }
    };
    $.fn.pageHide = function (targetPageId, params) {
        var obj = this;
        NP_history.push(obj, targetPageId, params);
        var pos = document.body.scrollTop;
        obj.attr('data-pos', pos);
        obj.find('[data-unload="refresh"]').each(function () {
            $(this).attr('pageNum', '1')
        });
        obj.niepHide();
        NP_component.loading(true)
    };
    $.fn.loadStaticImg = function (isPrev) {
        var obj = this;
        if (isPrev) return false;
        obj.find('img').each(function () {
            var ts = $(this);
            var statics = ts.data('static');
            if ( !! statics) {
                ts.attr('src', statics)
            }
        })
    };
    $.fn.pageList = function (datas, tips) {
        var ele = this;
        var tips = datas.emptyTip;
        if (!tips) tips = 'Sorry,暂无数据哦~';
        var list = datas.page.list;
        var baseObj;
        var modal = ele.children().eq(0);
        var modalHtml = NP_component.getEleHtml(modal);
        var prevLoad = ele.data('prevLoad');
        var component = ele.attr('data-component-refresh-loaded');
        var unloadType = ele.data('unload');
        var pageNum = datas.page.pageNumber;
        var totalPage = datas.page.totalPage;
        if (!component) {
            ele.attr('data-component-refresh-loaded', true);
            NP_component.setComponent(ele, modalHtml);
            ele.empty()
        } else {
            if (pageNum == 1) {
                ele.empty()
            }
            modalHtml = NP_component.getComponent(ele)
        }
        if (list.length == 0) {
            ele.html('<div style="text-align:center;font-size:12px;color:#bbb;">' + tips + '</div>').css('padding', '20px');
            return
        }
        var moreBtn = ele.find('.getMoreDataBtn');
        if (moreBtn.length == 0) {
            moreBtn = $('<a href="javascript:;" class="getMoreDataBtn">加载更多…</a>');
            ele.append(moreBtn)
        }
        var allObj = [];
        for (var i in list) {
            baseObj = NP_component.fill(modalHtml, list[i], prevLoad);
            baseObj.find('if').each(function () {
                var key = $(this).data('key');
                if (list[i][key] != $(this).data('value')) {
                    $(this).remove()
                } else {
                    $(this).next('else').remove()
                }
            });
            if ( !! datas.deal && typeof datas.deal != 'undefined' || datas.deal != undefined) {
                datas.deal(baseObj, i)
            }
            allObj.push(baseObj.prop('outerHTML'))
        }
        if (datas.cutMore == true) {
            ele.html(allObj.join(''))
        } else {
            moreBtn.before(allObj.join(''))
        }
        if (pageNum == totalPage || datas.cutMore == true) {
            moreBtn.remove();
            if (datas.cutMore == true) {
                if (pageNum == totalPage) {
                    ele.attr('pageNum', 1)
                } else {
                    ele.attr('pageNum', pageNum + 1)
                }
            }
        } else if (pageNum != totalPage && (!prevLoad || (prevLoad && (unloadType == 'once' || unloadType == 'false')))) {
            ele.attr('pageNum', pageNum + 1)
        }
    };
    $.fn.list = function (datas) {
        var ele = this;
        var tips = datas.emptyTip;
        var list = datas.list;
        if (!tips) tips = 'Sorry,暂无数据哦~';
        var baseObj;
        var modal = ele.children().eq(0);
        var modalHtml = NP_component.getEleHtml(modal);
        var prevLoad = ele.data('prevLoad');
        var component = ele.attr('data-component-refresh-loaded');
        if (!component) {
            ele.attr('data-component-refresh-loaded', true);
            NP_component.setComponent(ele, modalHtml);
            ele.empty()
        } else {
            ele.empty();
            modalHtml = NP_component.getComponent(ele)
        }
        if (list.length == 0) {
            ele.html('<div style="text-align:center;font-size:12px;color:#333;">' + tips + '</div>').css('padding', '20px');
            return
        }
        for (var i in list) {
            baseObj = NP_component.fill(modalHtml, list[i], prevLoad);
            if ( !! datas.deal && typeof datas.deal != 'undefined' || datas.deal != undefined) {
                datas.deal(baseObj, i)
            }
            ele.append(baseObj)
        }
    };
    $.fn.fill = function (datas, deal) {
        var ele = this;
        var objects = {};
        if ( !! datas) {
            objects = datas
        }
        objects['host'] = NP_config.host;
        var html = ele.html();
        if (!html) return false;
        var component = ele.attr('data-component-refresh-loaded');
        if (!component) {
            ele.attr('data-component-refresh-loaded', true);
            NP_component.setComponent(ele, html)
        } else {
            html = NP_component.getComponent(ele)
        }
        var holder, val;
        for (var key in objects) {
            holder = new RegExp(NP_config.start + key + NP_config.end, "g");
            val = objects[key];
            html = html.replace(holder, val)
        }
        var baseObj = $(html);
        var prevLoad = ele.data('prevLoad');
        NP_component.loadImg(baseObj, prevLoad);
        if ( !! deal && typeof deal != 'undefined' || deal != undefined) {
            deal(baseObj)
        }
        ele.html(baseObj);
        ele.find('if').each(function () {
            var key = $(this).data('key');
            if (objects[key] != $(this).data('value')) {
                $(this).remove()
            } else {
                $(this).next('else').remove();
                $($(this).html()).insertAfter($(this));
                $(this).remove()
            }
        })
    };
    $.fn.fillData = function (data, deal) {
        var ele = this;
        var className, obj;
        for (var key in data) {
            className = 'data_' + key;
            obj = ele.find('input.' + className + ' , select.' + className + ' , textarea.' + className + 'select.' + className);
            if (obj.length != 0) {
                obj.val(data[key])
            } else {
                obj = ele.find('img.' + className);
                if (obj.length != 0) {
                    var url = data[key];
                    obj.attr('data-loading', url)
                } else {
                    obj = ele.find('.' + className);
                    if (obj.length != 0) {
                        obj.text(data[key])
                    }
                }
            }
        }
        var prevLoad = ele.data('prevLoad');
        NP_component.loadImg(ele, prevLoad);
        if ( !! deal && typeof deal != 'undefined' || deal != undefined) {
            deal()
        }
    };
    $.fn.getBaseObj = function () {
        var baseHtml = $('#' + this.data('cmd')).html();
        return $(baseHtml)
    };
    $.fn.getObj = function () {
        var ele = this;
        var baseHtml = ele.html();
        var component = ele.attr('data-component-refresh-loaded');
        if (!component) {
            ele.attr('data-component-refresh-loaded', true);
            NP_component.setComponent(ele, baseHtml)
        } else {
            baseHtml = NP_component.getComponent(ele)
        }
        return $(baseHtml)
    };
    $.fn.niepShow = function () {
        this.addClass(NP_config.showClass)
    };
    $.fn.niepHide = function () {
        this.removeClass(NP_config.showClass)
    };
    $.fn.finished = function () {
        var component = this;
        var page = component.parents("." + NP_config.baseClass);
        var count = page.attr('data-count');
        if (!count) {
            count = 0
        } else {
            count = count - 1
        }
        page.attr('data-count', count);
        var prevLoad = component.data('prevLoad');
        if (count == 0 && prevLoad != 'need') {
            page.pageShow()
        } else if (prevLoad == 'need') {
            component.data('prevLoad', 'completed')
        }
        var clone = page.data('clone');
        if (clone == 'cloneBody' && component.attr('data-unload') == 'loaded') {
            var ontology = $('#' + page.attr('data-ontology')).find('[data-unload="static"]');
            ontology.each(function () {
                if ($(this).data('cmd') == component.data('cmd')) {
                    $(this).after($(component.clone()));
                    $(this).remove()
                }
            })
        }
    };
    $.fn.ajaxFinished = function (result, success) {
        var component = this;
        var status = result.status;
        if (status == '200') {
            success(result);
            component.finished()
        } else if (status == '800') {
            NP_component.refreshCmd('page_chapter');
            NP_component.switchPage({
                target: 'needPay',
                params: result.message
            })
        } else if (status == '100') {
            NP_component.refreshCmd('info_user');
            var page = result.message;
            var random = Math.random(9000) + 1000;
            location.href = NP_config.host + "/getCode?page=" + page + "&params=1#" + random
        } else {
            alerted(result.message)
        }
    };
    $.fn.post = function (postJson, success) {
        var component = this;
        var url = NP_config.service + "/" + component.data('cmd').replace(new RegExp('_', 'g'), '/');
        $.post(url, postJson, function (result) {
            success(result)
        }, 'json')
    };
    $.fn.pagePost = function (postJson, success) {
        var component = this;
        var jsons = {};
        if (!jQuery.isFunction(postJson)) {
            jsons = !! postJson ? postJson : {}
        }
        jsons['pageNum'] = component.attr('pageNum') || 1;
        var url = NP_config.service + "/" + component.data('cmd').replace(new RegExp('_', 'g'), '/');
        $.post(url, jsons, function (result) {
            if (jQuery.isFunction(postJson)) {
                postJson(result)
            } else if (jQuery.isFunction(success)) {
                success(result)
            }
        }, 'json')
    }
})(jQuery);
window.onpopstate = function (ev) {
    NP_history.back()
};
$('body').on('click', '.getMoreDataBtn', function () {
    var ts = $(this);
    var parent = ts.parent();
    var page = ts.parents('.' + NP_config.baseClass);
    var params = page.attr('data-params');
    var cmd = eval(parent.data('cmd'));
    new cmd(parent, params, page)
});
$('body').on('click', '[data-action="switch"] , [data-action="search"]', function (e) {
    e.preventDefault();
    var showingPage = Niep.getShowPage();
    var ts = $(this);
    if (ts.data('action') == 'search') {
        var name = ts.data('name');
        var linkInp = showingPage.find('input[name="' + name + '"]');
        ts.attr('data-params', name + ":" + linkInp.val())
    }
    var cmd = ts.data('cmd');
    if ( !! cmd) {
        var cmds = eval(cmd);
        new cmds(ts)
    }
    var params = ts.attr('data-params');
    var tId = "page_" + ts.attr('href');
    if (showingPage.length != 0) {
        showingPage.pageHide(tId, params)
    } else {
        var targetPageId = tId;
        targetPageId = "page=" + targetPageId.split('_')[1];
        if ( !! params) {
            targetPageId = targetPageId + "&params=" + params
        }
        if ( !! NP_DATA.historyAction) {
            targetPageId = NP_DATA.historyAction + "?" + targetPageId
        }
        history.pushState('', '', targetPageId)
    }
    NP_component.loading(true);
    var target = $('#' + tId);
    if (target.length == 0) {
        NP_component.loadPage(ts.attr('href'), function (result) {
            target = $(result);
            target.attr('id', tId);
            $('body').prepend(target);
            NP_component.loadResources(params, target, ts)
        })
    } else {
        NP_component.loadResources(params, target, ts)
    }
});

function changeNum(num) {
    var arr = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
    var t = (num + '').split('');
    if (num < 10) {
        return arr[num]
    } else if (num < 100) {
        if (t[1] == 0) {
            return arr[t[0]] + '十'
        }
        return arr[t[0]] + '十' + arr[t[1]]
    } else if (num < 1000) {
        if (t[2] == 0) {
            if (t[1] == 0) {
                return arr[t[0]] + '百'
            }
            return arr[t[0]] + '百' + arr[t[1]] + '十'
        } else {
            if (t[1] == 0) {
                return arr[t[0]] + '百零' + arr[t[2]]
            }
        }
        return arr[t[0]] + '百' + arr[t[1]] + '十' + arr[t[2]]
    } else {
        return num
    }
}
function getJsons(str, keys) {
    str = str + '';
    var json = {};
    if (!str) {
        return json
    } else if (str.indexOf('-') == -1) {
        json[keys[0]] = str
    } else {
        var arr = str.split('-');
        for (var i = 0; i < arr.length; i++) {
            json[keys[i]] = arr[i]
        }
    }
    return json
}
function getTotalCount(count) {
    var counts = "" + count;
    if (count < 99999) {
        return counts
    } else {
        return counts.substr(0, counts.length - 4) + "万"
    }
}
function changeParamsToJson(params) {
    var paramsJson = {};
    if (!params) {
        return paramsJson
    }
    params.replace('?', '');
    var arr = params.split("~~");
    for (var i = 0; i < arr.length; i++) {
        var pairs = arr[i];
        var pos = pairs.indexOf(':');
        if (pos == -1) continue;
        paramsJson[pairs.substring(0, pos)] = decodeURI(pairs.substring(pos + 1))
    }
    return paramsJson
}
function page_novel(ts, params, page) {
    var json;
    params = ts.attr('data-params') || params;
    json = changeParamsToJson(params);
    ts.pagePost(json, function (result) {
        ts.ajaxFinished(result, function () {
            var cut = ts.data('cut');
            for (var i = 0; i < result.page.list.length; i++) {
                var obj = result.page.list[i];
                obj['totalCount'] = getTotalCount(obj.count)
            }
            result['deal'] = function (obj, i) {
                if (i == 0) {
                    obj.find('.column-1').remove()
                } else if (cut == 'recom') {
                    obj.find('.column-2').remove()
                }
            };
            if ( !! cut) {
                result['cutMore'] = true
            }
            result['emptyTip'] = 'Sorry，暂时还没有相关小说哦~';
            ts.pageList(result);
            var nName = json.nName;
            if ( !! nName) {
                page.find('input[name="nName"]').val(nName)
            }
            page.find('.line-novel a.cur').removeClass('cur');
            page.find('.line-novel a').each(function () {
                var ts = $(this);
                if (params.indexOf(ts.attr('data-base')) > -1) {
                    ts.addClass('cur')
                }
            })
        })
    })
}
function info_novel(ts, params, page) {
    ts.post({
        id: params
    }, function (res) {
        ts.ajaxFinished(res, function () {
            var data = res.data;
            data['zNum'] = changeNum(data.lChapterNum); //最后一章章节数
            var arr = ['朕觉此书甚好，要赏！', '今天心情真不错，赏！', '作者帅得不得了，必须赏！'];
            var i = parseInt(parseInt(Math.random() * arr.length, 10));
            data['goodWord'] = arr[i];
            ts.fill(res.data);
            if (data.isEnd) {
                ts.find('.is-serialize').remove()
            } else {
                ts.find('.is-finish').remove()
            }
            var history = res.history;
            if ( !! history) {
                ts.find('.control-btn a.start').eq(0).attr('data-params', history.chapterNum + '-' + history.novelId);
                if (history.isFavorite) {
                    ts.find('.control-btn a.start').eq(1).attr({
                        'href': '/delete/history?id=' + history.id,
                        'data-type': '0'
                    }).text('已加入书架')
                }
            }
            var givings = res.givings;
            if ( !! givings) {
                var arrs = [];
                arrs.push('<div class="givings-wrapper">');
                arrs.push('<div class="giving">');
                arrs.push('<div class="userPhoto"></div><div class="userPhoto-sec">' + givings.coins + ' 书币</div>');
                arrs.push('</div>');
                arrs.push('<div class="options"><div>多谢客官打赏，这 <span class="text-yellow">' + givings.coins + '</span> 个书币可是客官掉的？</div>');
                arrs.push('<a href="/update/givings?type=0&novelId=' + givings.novelId + '" data-send="true" data-success="givingsSuccess" class="pickBtn">不是我的</a>');
                arrs.push('<a href="/update/givings?type=1&novelId=' + givings.novelId + '" data-send="true" data-success="givingsSuccess" class="pickBtn pickBtn-default">收入囊中</a>');
                arrs.push('</div>');
                arrs.push('</div>');
                page.append(arrs.join(''))
            }
            $.post(NP_config.host + "/save/readTimes?id=" + params)
        })
    })
}
function list_classify(ts, params, page) {
    ts.post(function (res) {
        ts.ajaxFinished(res, function () {
            var list = res.list;
            if ( !! page && page.attr('id').indexOf('page_novelList') > -1) {
                ts.list(res)
            } else {
                var html = [];
                for (var i = 0; i < list.length; i++) {
                    var obj = list[i];
                    if (!obj.parentId) {
                        html.push('<div class="panel panel-room"><div class="panel-header"><a href="novelList" class="left" data-action="switch" data-params="10-99-99-99- -' + obj.id + '"><span class="font book">&#xe60b;</span>' + obj.cName + '</a></div>');
                        html.push('<div class="panel-body">');
                        for (var j = 0; j < list.length; j++) {
                            var child = list[j];
                            if (child.parentId == obj.id) {
                                html.push('<div class="item"><a class="name" href="novelList" data-action="switch" data-params="10-99-99-99- -' + child.id + '">' + child.cName + '</a></div>')
                            }
                        }
                        html.push('</div>');
                        html.push('</div>')
                    }
                }
                ts.html($(html.join('')));
                ts.find('.panel-body').each(function () {
                    if ($(this).find('.item').length == 0) {
                        $(this).remove()
                    }
                })
            }
        })
    })
}
function page_chapter(ts, params, page) {
    var json = getJsons(params, ['pageNum', 'novelId', 'channelId']);
    if ( !! ts.attr('pageNum')) {
        json['pageNum'] = ts.attr('pageNum')
    }
    ts.post(json, function (res) {
        ts.ajaxFinished(res, function () {
            var chapter = res.page.list[0];
           // console.log('json------->'+json);
          //  console.log('chapter------->'+chapter.content);
            
            
            
            var isFirst = res.page.firstPage;
            var isLast = res.page.lastPage;
            if (!isFirst) {
                chapter['prevNum'] = chapter.number - 1
            } else {
                page.find('.flex-chapter .item').eq(0).addClass('disabled').attr({
                    'data-action': '',
                    'href': 'javascript:;'
                })
            }
            if (!isLast) {
                chapter['nextNum'] = chapter.number + 1
            } else {
                page.find('.flex-chapter .item').eq(2).addClass('disabled').attr({
                    'data-action': '',
                    'href': 'javascript:;'
                })
            }
            chapter['zNum'] = changeNum(chapter.number);
           
            //alert('zNum 2'+changeNum(chapter.number));
            
            ts.fill(chapter);
            var fz = parseInt(getCookie('fontSize')) || 16;
            $('.chapter-content').css({
                'font-size': fz + 'px'
            });
            var index = parseInt(getCookie('bagPic')) || 0;
            $('body').attr('class', 'chapterInfo bag' + index);
            $('.colorBlock').css('background-image', 'url(../img/bag' + index + '.png)');
            var novelName = chapter.nName;
          
            page.attr('data-title', novelName);
            document.title = novelName;
            
            $.post(NP_config.host + "/save/history?novelId=" + chapter.novelId + "&chapterNum=" + chapter.number, function () {
                NP_component.refreshCmd('page_history')
            });
            
         //   alert('进入章节');
        //    alert('chapter的id-->'+$('.index').attr("data-title","百合书屋"));
            $.post(NP_config.host + "/property/qr", function (data) {
                page_qr(data.property);
             });   
            
            var qd = getQueryParamsJson().qd;
            if ( !! qd && qd.indexOf('-') != -1) {
                var qdArr = qd.split('-');
                if (qdArr.length == 2 && qdArr[1] == '0') {
                    $('html').addClass('noQd')
                }
            }
        })
    })
}

function page_qr(e){
	$('.panel_qr').empty();
	var wx_content = {};
	wx_content.accounts = 
	'&nbsp'+e.public_name+'</b>，在<b>&nbsp'+e.public_name+'</b>的<b>&nbsp粉丝福利&nbsp</b>菜单点击<b>&nbsp继续阅读</b>，同时可点击<b>&nbsp领取书券&nbsp</b>，就可获得<b>&nbsp100书币&nbsp</b>哦!</div>' + '<div class="panel-body"> <div class="small-tip">长按下方二维码，关注<b>'+e.public_name+'</b>，送100书币 </div>';
	wx_content.qr = '<img src="'+e.qrcode+'" data-static="'+e.qrcode+'" width="120px" alt="'+e.public_name+'"/>'
	$('.panel_qr').append('<div class="panel-footer"> <b>如何追书：</b>关注公众号<b>' + wx_content.accounts + wx_content.qr + '</div>')
}



function getQueryParamsJson() {
    var paramsJson = {};
    var href = location.href;
    var queryStr = location.search;
    if (!queryStr) return paramsJson;
    var arr = location.search.substring(1).split("&");
    for (var i = 0; i < arr.length; i++) {
        var pairs = arr[i];
        var pos = pairs.indexOf('=');
        if (pos == -1) continue;
        paramsJson[pairs.substring(0, pos)] = decodeURI(pairs.substring(pos + 1))
    }
    return paramsJson
}
function page_chapters(ts, params, page) {
    var id = page.attr('id');
    var json = getJsons(params, ['pageNum', 'novelId', 'pageSize', 'orderType']);
    if (id.indexOf('page_chapterListDesc') != -1) {
        json['orderType'] = 1
    }
    if ( !! ts.attr('pageNum')) {
        json['pageNum'] = ts.attr('pageNum')
    }
    ts.post(json, function (res) {
        ts.ajaxFinished(res, function () {
            if (id.indexOf('page_chapterList') != -1 || id.indexOf('page_chapterListDesc') != -1) {
                for (var i = 0; i < res.page.list.length; i++) {
                    var obj = res.page.list[i];
                    obj['zNum'] = changeNum(obj.number) //每一个章节数
                }
                ts.pageList(res)
            } else {
                var chapter = res.page.list[0];
                chapter['time'] = chapter.time.substr(0, 16);
                chapter['zNum'] = changeNum(chapter.number);
                ts.fill(chapter)
            }
        })
    })
}
function info_user(ts, params, page) {
    var para = ts.data('params');
    ts.post({
        page: para
    }, function (res) {
        ts.ajaxFinished(res, function () {
            var data = res.data;
            var id = page.attr('id');
            if (!data) {
                data = {
                    'coins': 0
                }
            }
            ts.fill(res.data);
            if (!res.data.isNew) {
                ts.find('.gift').remove()
            }
            if ( !! data.isOpen) {
                ts.find('.checkbox input').prop('checked', true)
            }
        })
    })
}
function page_comment(ts, params, page) {
    var para = ts.data('params');
    ts.pagePost(para, function (res) {
        ts.ajaxFinished(res, function () {
            res['emptyTip'] = 'Sorry,暂无评论哦~';
            for (var i = 0; i < res.page.list.length; i++) {
                var obj = res.page.list[i];
                obj['time'] = obj.time.substr(0, 16)
            }
            ts.pageList(res);
            page.find('.commentCount').text(res.page.totalRow)
        })
    })
}
function page_recharge(ts, params) {
    ts.pagePost(ts.data('params'), function (res) {
        ts.ajaxFinished(res, function () {
            for (var i = 0; i < res.page.list.length; i++) {
                var obj = res.page.list[i];
                obj['amountY'] = (obj.amount * 0.01).toFixed(2);
                obj['time'] = (obj.time).substr(0, 16)
            }
            res['emptyTip'] = 'Sorry,暂时还没有充值记录哦~';
            res['deal'] = function (obj, j) {
                if (res.page.list[j].type == 2) {
                    obj.addClass('content-give')
                }
            };
            ts.pageList(res)
        })
    })
}
function page_history(ts, params, page) {
    var id = page.attr('id');
    var json = id == 'page_collections' ? {
        isFavorite: 1
    } : '';
    ts.pagePost(json, function (res) {
        ts.ajaxFinished(res, function () {
            for (var i = 0; i < res.page.list.length; i++) {
                var obj = res.page.list[i];
                obj['zNum'] = changeNum(obj.chapterNum)
               // alert('zNum 5'+changeNum(obj.chapterNum)); 
            }
            ts.pageList(res)
        })
    })
}
function info_signIn(ts, params, page) {
    ts.post(function (res) {
        ts.ajaxFinished(res, function () {
            var data = res.data || {
                score: 0,
                days: 0
            };
            var now = new Date();
            var time = new Date(data.time);
            if ( !! data.time && (now.getFullYear() == time.getFullYear() && now.getDate() - time.getDate() > 1 && now.getMonth() == time.getMonth())) {
                data['days'] = 0;
                data['dScore'] = 1
            }
            data['dScore'] = data.days < 7 ? data.days + 1 : data.days;
            ts.fill(data);
            if (now.getFullYear() == time.getFullYear() && now.getDate() == time.getDate() && now.getDate() == time.getDate()) {
                page.find('.date').attr({
                    'href': 'javascript:;',
                    'data-send': ''
                }).text('今日已签到').addClass('disabled')
            }
            if (data.score < 10) {
                page.find('.getCoins').remove()
            }
        })
    })
}
function info_history(ts, params) {
    ts.post(function (res) {
        ts.ajaxFinished(res, function () {
            var data = res.data;
            if ( !! data) {
                data['zNum'] = changeNum(data.number); //历史阅读的章节数
                ts.fill(data);
                ts.show()
            } else {
                ts.hide()
            }
        })
    })
}
function checkUserAgent(ts, params, page) {
    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        ts.children('a').remove()
    } else {
        ts.children('div').remove()
    }
    ts.finished()
}
function page_maxReadTimes(ts, params, page) {
    ts.pagePost(function (res) {
        ts.ajaxFinished(res, function () {
            ts.pageList(res)
        })
    })
}
function page_freeBooks(ts, params, page) {
    ts.pagePost(function (res) {
        ts.ajaxFinished(res, function () {
            ts.pageList(res)
        })
    })
}
var mReg = /^1[3|4|5|8|7][0-9]\d{8}$/;
var pReg = /^[1-9]{1}[0-9]*([.]{1}[0-9]{1,2})?$/;

function checkData(ele) {
    var eVal = ele.val();
    var itemName = ele.parents('.form-group').find('label').text();
    if (!itemName) {
        itemName = ele.attr('placeholder');
        if ( !! itemName) {
            itemName = itemName.replace('请输入', '')
        }
    }
    var isEmpty = ele.data('empty');
    if (!isEmpty && !eVal) {
        alerted(itemName + "不能为空", "shake");
        return false
    }
    if ( !! isEmpty && eVal == isEmpty) {
        alerted("请选择" + itemName, "shake");
        return false
    }
    var minLen = ele.data('min');
    var maxLen = ele.data('max');
    if (( !! minLen && eVal.length) < minLen || ( !! maxLen && eVal.length > maxLen)) {
        var text = itemName + "的长度为" + minLen + "~" + maxLen + "个字符";
        if (minLen == maxLen) text = itemName + "输入错误";
        if (!minLen) text = itemName + "的最大长度为" + maxLen + "个字符";
        if (!maxLen) text = itemName + "的最小长度为" + minLen + "个字符";
        alerted(text, "shake");
        return false
    }
    var type = ele.data('type');
    if (isEmpty != true || !! eVal) {
        if ((type == 'mobile') && !mReg.test(eVal)) {
            alerted(itemName + "不正确", "shake");
            return false
        }
        if ((type == 'id') && !IdentityCodeValid(eVal)) {
            alerted(itemName + "不正确", "shake");
            return false
        }
        if (type == 'amount' && !pReg.test(eVal)) {
            alerted(itemName + "不正确", "shake");
            return false
        }
        if (type == 'int' && eVal.indexOf('.') != -1) {
            alerted(itemName + "只允许输入整数", "shake");
            return false
        }
    }
    return true
}
var formResult = true;
$('body').on('click', 'a[data-submit="true"]', function (eve) {
    eve.preventDefault();
    var _this = $(this);
    NP_component.loading(true);
    var form = _this.parents('form');
    var result = true;
    var postJson = {};
    form.find(' select , input , textarea ').not('input[type="file"],input[type="checkbox"],input[type="radio"],input[type="hidden"]').each(function (i, e) {
        var obj = $(this);
        if (!checkData(obj)) {
            result = false;
            return false
        }
        var name = obj.attr('name');
        if ( !! name) postJson[name] = obj.val()
    });
    if (!result) {
        NP_component.loading(false);
        return false
    }
    var addedCheck = _this.data('check');
    if ( !! addedCheck) {
        var checkFn = eval(addedCheck);
        new checkFn(_this, result)
    }
    if (!formResult) {
        NP_component.loading(false);
        return false
    }
    var vals = [];
    form.find('input[type="checkbox"]:checked ').each(function (i, e) {
        var obj = $(this);
        var name = obj.attr('name');
        vals.push(obj.val());
        if ( !! name) postJson[name] = vals.join(',')
    });
    form.find('input[type="radio"]:checked, input[type="hidden"]').each(function (i, e) {
        var obj = $(this);
        var name = obj.attr('name');
        if ( !! name) postJson[name] = obj.val()
    });
    var url = NP_config.service + _this.attr('href');
    var cmd = _this.data('cmd');
    var error = _this.data('error');
    var alertText = _this.data('alert');
    var direct = _this.data('redirect');
    $.post(url, postJson, function (result) {
        NP_component.loading(false);
        var msg = result.status;
        var tip = result.message;
        if (msg == '200') {
            if ( !! direct) {
                var params = _this.data('params') || '';
                NP_component.switchPage({
                    target: direct,
                    params: params
                })
            }
            if ( !! cmd) {
                var cmds = eval(cmd);
                new cmds(_this, result)
            }
            if ( !! alertText) {
                alerted(alertText)
            }
        } else if (msg == '100') {
            alerted(tip)
        } else {
            if ( !! error) {
                var errors = eval(error);
                new errors(_this, result)
            }
            alerted(tip)
        }
    }, 'json')
});
$('body').on('click', 'a[data-send="true"]', function (eve) {
    eve.preventDefault();
    NP_component.loading(true);
    var _this = $(this);
    var url = NP_config.host + _this.attr('href');
    var callBack = _this.attr('data-success');
    var redirect = _this.attr('data-redirect');
    $.post(url, function (result) {
        NP_component.loading(false);
        var status = result.status;
        var tip = result.message;
        if (status == "200") {
            if ( !! callBack) {
                var fn = eval(callBack);
                new fn(_this, result)
            } else if ( !! redirect) {
                window.location.href = host + redirect
            } else {
                NP_component.small(tip, 3000, true)
            }
        } else if (status == "100") {
            alerted(tip)
        } else {
            alerted(tip)
        }
    }, 'json')
});

function alerted(t) {
    alert(t)
}
var w = $(window).width();
var h = $(window).height();
$('body').css('min-height', h + 'px');
$('body').on('click', '[data-cmd="resetFont"]', function () {
    var ts = $(this);
    var fontSize = parseInt(getCookie("fontSize")) || 14;
    var type = ts.data('type');
    if (type == '1') {
        fontSize += 2
    } else {
        fontSize -= 2
    }
    if (fontSize >= 28 || fontSize < 12) return false;
    $('.chapter-content').css({
        'font-size': fontSize + 'px'
    });
    setCookie("fontSize", fontSize, 30)
});
$('body').on('click', '[data-cmd="resetColor"]', function () {
    var ts = $(this);
    var index = parseInt(getCookie("bagPic")) || 0;
    index++;
    if (index == 6) {
        index = 0
    }
    $('.colorBlock').css('background-image', 'url(../img/bag' + index + '.png)');
    $('body').attr('class', 'chapterInfo bag' + index);
    setCookie("bagPic", index, 30)
});

function resetBtn(btn, result) {
    var collect = btn.parents('.page').find('.collect');
    var times = parseInt(collect.attr('data-times'));
    var type = btn.attr('data-type');
    if (type == '1') {
        btn.attr({
            'href': '/delete/history?id=' + result.message,
            'data-type': '0'
        }).text('已加入书架');
        NP_component.small("已加入书架");
        times++;
        collect.attr('data-times', times).text(times)
    } else {
        btn.attr({
            'href': '/save/history?isFavorite=true&novelId=' + result.message,
            'data-type': '1'
        }).text('加入书架');
        NP_component.small("已从书架移除");
        if (times > 0) {
            times--;
            collect.attr('data-times', times).text(times)
        }
    }
    NP_component.refreshCmd('page_history')
}
$('body').on('click', '.backTop', function () {
    $('body,html').animate({
        scrollTop: 0
    }, 400)
});
$('body').on('click', function () {
    $('.searchList').hide()
});
$('body').on('click', '[data-cmd="getNovelList"]', function () {
    var prev = $(this).prev().find('.linkGroup');
    page_novel(prev)
});

function searchChapter(obj) {
    var ts = $(obj);
    var title = ts.val();
    var id = ts.data('id');
    var searchList = ts.parent().next();
    if ( !! title) {
        var url = NP_config.host + "/page/chapterByTitle";
        $.post(url, {
            title: title,
            novelId: id
        }, function (result) {
            var status = result.status;
            if (status == '200') {
                var page = result.page;
                var totalRow = page.list.length;
                if (totalRow > 0) {
                    var html = [];
                    for (var i = 0; i < page.list.length; i++) {
                        var obj = page.list[i];
                        html.push('<a href="chapterInfo" data-action="switch" ');
                        html.push(' data-params="' + obj.number + '-' + obj.novelId + '" class="item">第' + obj.number + '章 ' + obj.title + '</a>')
                    }
                    searchList.html(html.join('')).show()
                } else {
                    searchList.empty().hide()
                }
            } else {
                searchList.empty().hide()
            }
        })
    } else {
        searchList.empty().hide()
    }
}
$('body').on('click', '[data-cmd="toSearchChapter"]', function () {
    var ts = $(this).prev();
    var title = ts.val();
    var id = ts.data('id');
    var searchList = ts.parent().next();
    if ( !! title) {
        var url = NP_config.host + "/page/chapterByTitle";
        $.post(url, {
            title: title,
            novelId: id
        }, function (result) {
            var status = result.status;
            if (status == '200') {
                var page = result.page;
                var totalRow = page.list.length;
                if (totalRow > 0) {
                    var html = [];
                    for (var i = 0; i < page.list.length; i++) {
                        var obj = page.list[i];
                        html.push('<a href="chapterInfo" data-action="switch" ');
                        html.push(' data-params="' + obj.number + '-' + obj.novelId + '" class="item">第' + obj.number + '章 ' + obj.title + '</a>')
                    }
                    searchList.html(html.join('')).show()
                } else {
                    searchList.empty().hide()
                }
            } else {
                searchList.empty().hide()
            }
        })
    } else {
        searchList.empty().hide()
    }
});
$('body').on('click', '[data-cmd="showSurprise"]', function () {
    var arrs = [];
    arrs.push('<div class="givings-wrapper">');
    arrs.push('<div class="giving">');
    arrs.push('<div class="userPhoto"></div><div class="userPhoto-sec">100书币</div>');
    arrs.push('</div>');
    arrs.push('<div class="options"><div>恭喜获得一个新手礼包，是否立即领取？</div>');
    arrs.push('<a href="/update/gift" data-send="true" data-success="newUserSuccess" class="pickBtn pickBtn-ins">立即领取</a>');
    arrs.push('</div>');
    arrs.push('</div>');
    $('body').append(arrs.join(''))
});
var timer = null;
var flag = true;
$(window).on('scroll', function () {
    var top = $(window).scrollTop();
    if (top > 100) {
        $('.backTop').fadeIn();
        clearInterval(timer);
        timer = setTimeout(function () {
            $('.backTop').hide()
        }, 3000)
    } else {
        $('.backTop').fadeOut()
    }
    var bottomDis = $(document).height() - $(window).height() - top;
    var showPage = NP_component.getShowPage();
    var getMoreDateBtn = showPage.find('.getMoreDataBtn');
    if ( !! getMoreDateBtn && getMoreDateBtn.length > 0) {
        var dis = getMoreDateBtn.parent().data('bottom') || 240;
        if (bottomDis < dis + 100 && bottomDis > dis - 100) {
            if (flag) {
                flag = false;
                getMoreDateBtn.click();
                setTimeout(function () {
                    flag = true
                }, 1000)
            }
        }
    }
});

function dealComment(btn, res) {
    NP_component.small('评论成功');
    NP_component.refreshCmd('page_comment');
    NP_component.switchPage({
        'target': 'novelInfo',
        'params': res.message
    })
}
function signInSuccess(btn, res) {
    NP_component.small(res.message);
    NP_component.refreshCmd('info_signIn');
    NP_component.switchPage({
        'target': 'signIn'
    })
}
function exchangeCoinsSuccess(btn, res) {
    NP_component.small(res.message);
    NP_component.refreshCmd('info_user');
    NP_component.refreshCmd('info_signIn');
    NP_component.switchPage({
        'target': 'userCenter'
    })
}
function buyRecordSuccess(btn, res) {
    NP_component.small(res.message);
    NP_component.refreshCmd('info_user');
    NP_component.switchPage({
        'target': 'chapterInfo',
        params: btn.attr('data-params')
    })
}
function givingsSuccess(btn, res) {
    NP_component.refreshCmd('info_user');
    if ( !! res.message) {
        NP_component.small(res.message)
    }
    $('.givings-wrapper').remove()
}
function newUserSuccess(btn, res) {
    NP_component.refreshCmd('info_user');
    if ( !! res.message) {
        NP_component.small(res.message)
    }
    $('.givings-wrapper , .gift').remove();
    NP_component.switchPage({
        target: 'userCenter'
    })
}
function changeOpenSuccess(btn, res) {
    NP_component.small(res.message);
    var inp = btn.prev();
    if (inp.prop('checked')) {
        inp.prop('checked', false)
    } else {
        inp.prop('checked', true)
    }
}
function createSuccess(btn, res) {
    NP_component.loading(true);
    var id = res.id;
    var payType = res.payType;
    if (payType == '1') {
        window.location.href = NP_config.host + "/alipay?id=" + id
    } else if (payType == '2') {
        window.location.href = NP_config.host + "/pay/pre?id=" + id
    } else if (payType == '3') {
        window.location.href = NP_config.host + "/update?id=" + id
    }
}
function resetParams(ts) {
    var inp = ts.parents('.single-line-form').find('input').val();
    ts.attr('data-params', '10-99-99-99-' + inp)
}
function collectParams(ts) {
    var params = ts.attr('data-base');
    ts.parents('.line-novel').siblings().find('a.cur').each(function () {
        var curParam = $(this).attr('data-base');
        if ( !! params && !! curParam) {
            params += '~~'
        }
        params += curParam
    });
    ts.attr('data-params', params)
}
$(function () {
    var timer = null;
    timer = setInterval(function () {
        if (!Niep) {} else {
            Niep.init({
                defaultPage: 'home',
                beforePageShow: function (page) {
                    var id = page.attr('id');
                    if ( !! id && id.indexOf('page_chapterInfo') != -1) {
                        $('body').addClass('chapterInfo')
                    } else {
                        $('body').removeClass('chapterInfo')
                    }
                    if(!!id && id.indexOf('page_home') != -1 ){
                        page.attr('data-title', $('body').attr('data-homeTitle') ) ;
                        document.title = $('body').attr('data-homeTitle') ;
                    }
                },
                afterPageShow: function (page) {
                    $.post(NP_config.host + "/save/pv")
                }
            });
            clearInterval(timer)
        }
    }, 1)
});
